<template>
  <div>
    <n-card title="需求列表">
      <template #header-extra>
        <n-select
          v-model:value="filters.status"
          placeholder="需求状态"
          :options="statusOptions"
          clearable
          style="width: 150px"
          @update:value="loadDemands"
        />
      </template>

      <n-space vertical size="large">
        <n-list hoverable>
          <n-list-item v-for="demand in demands" :key="demand.id">
            <n-thing>
              <template #avatar>
                <n-avatar>
                  <n-icon><DocumentTextOutline /></n-icon>
                </n-avatar>
              </template>
              <template #header>
                <n-space align="center">
                  <span @click="router.push(`/demand/detail/${demand.id}`)" style="cursor: pointer;">
                    {{ demand.title }}
                  </span>
                  <n-tag v-if="demand.status === 'PENDING'" type="warning" size="small">待接单</n-tag>
                  <n-tag v-else-if="demand.status === 'ASSIGNED'" type="info" size="small">已分配</n-tag>
                  <n-tag v-else-if="demand.status === 'IN_PROGRESS'" type="primary" size="small">服务中</n-tag>
                  <n-tag v-else-if="demand.status === 'COMPLETED'" type="success" size="small">已完成</n-tag>
                </n-space>
              </template>
              <template #description>
                <n-space size="small">
                  <n-text depth="3">
                    <n-icon><PersonOutline /></n-icon>
                    {{ demand.demanderName }}
                  </n-text>
                  <n-text depth="3">
                    <n-icon><LocationOutline /></n-icon>
                    {{ demand.address }}
                  </n-text>
                  <n-text depth="3">
                    <n-icon><TimeOutline /></n-icon>
                    {{ formatDate(demand.expectedTime) }}
                  </n-text>
                  <n-text depth="3">
                    <n-icon><TrophyOutline /></n-icon>
                    {{ demand.pointsReward }}积分
                  </n-text>
                </n-space>
              </template>
              {{ demand.description }}
              <template #action>
                <n-space>
                  <n-button size="small" @click="router.push(`/demand/detail/${demand.id}`)">
                    查看详情
                  </n-button>
                  <n-button
                    v-if="demand.status === 'PENDING'"
                    type="primary"
                    size="small"
                    @click="handleApply(demand)"
                  >
                    我要接单
                  </n-button>
                </n-space>
              </template>
            </n-thing>
          </n-list-item>
        </n-list>

        <n-pagination
          v-model:page="pagination.page"
          :page-count="pagination.pageCount"
          :page-size="pagination.pageSize"
          show-size-picker
          :page-sizes="[10, 20, 30, 40]"
          @update:page="loadDemands"
          @update:page-size="handlePageSizeChange"
        />
      </n-space>
    </n-card>

    <n-modal v-model:show="applyModalVisible" preset="dialog" title="申请服务需求">
      <n-form :model="applyForm">
        <n-form-item label="申请理由">
          <n-input
            v-model:value="applyForm.reason"
            type="textarea"
            placeholder="请说明您的优势和可以提供的帮助"
            :rows="4"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="applyModalVisible = false">取消</n-button>
          <n-button type="primary" @click="confirmApply">确认申请</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getDemandList, applyDemand } from '@/api/demand'
import { DocumentTextOutline, PersonOutline, LocationOutline, TimeOutline, TrophyOutline } from '@vicons/ionicons5'

const router = useRouter()
const userStore = useUserStore()

const demands = ref([])
const filters = reactive({
  status: null
})
const pagination = reactive({
  page: 1,
  pageSize: 10,
  pageCount: 1
})

const applyModalVisible = ref(false)
const applyForm = reactive({
  demandId: null,
  reason: ''
})

const statusOptions = [
  { label: '待接单', value: 'PENDING' },
  { label: '已分配', value: 'ASSIGNED' },
  { label: '服务中', value: 'IN_PROGRESS' },
  { label: '已完成', value: 'COMPLETED' }
]

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString('zh-CN')
}

const loadDemands = async () => {
  try {
    const res = await getDemandList({
      page: pagination.page,
      size: pagination.pageSize,
      status: filters.status
    })
    demands.value = res.data.records || []
    pagination.pageCount = res.data.pages || 1
  } catch (error) {
    console.error('加载需求失败:', error)
  }
}

const handlePageSizeChange = (pageSize) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  loadDemands()
}

const handleApply = (demand) => {
  applyForm.demandId = demand.id
  applyForm.reason = ''
  applyModalVisible.value = true
}

const confirmApply = async () => {
  try {
    await applyDemand(applyForm.demandId, {
      userId: userStore.userId,
      reason: applyForm.reason
    })
    window.$message?.success('申请成功')
    applyModalVisible.value = false
    loadDemands()
  } catch (error) {
    console.error('申请失败:', error)
  }
}

onMounted(() => {
  loadDemands()
})
</script>

